#ifndef     __TIME_SYNC_H
#define     __TIME_SYNC_H

#include <chrono>
#include <mutex>
#include <condition_variable>

class TimeSync {

public:
    using TimePoint = std::chrono::high_resolution_clock::time_point;
    using Duration = std::chrono::high_resolution_clock::duration;

    bool wait(const Duration &duration) {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_cond.wait_until(lock, m_base + duration, [this](){
            return m_exit_flag;
        });
        return !m_exit_flag;
    }

    void exit() {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_exit_flag = true;
        m_cond.notify_one();
    }

private:
    std::mutex m_mutex;
    std::condition_variable m_cond;
    TimePoint m_base = std::chrono::high_resolution_clock::now();
    bool m_exit_flag = false;
};

#endif
